import React, { useRef, useState, useEffect } from 'react';
import { connect } from 'dva';
import { Card, Select, Tooltip, Button, Modal, message } from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import Ellipsis from '@/components/Ellipsis';
import styles from '@/components/common/PateoTable/TableList.less';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { PlusOutlined } from '@ant-design/icons';
import { routerRedux } from 'react-router-dom';

const DEFAULT_QUERY = () => ({
  seriesCode: '',
  groupCode: ''
})

const mapStateToProps = (state: any) => {
  return {
    listData: state?.chargingLimitConfig?.pageData,
    loading: state.loading.effects['chargingLimitConfig/getFetchPage'],
    dicData: state?.menu?.dicData ?? {},
    userProfile: state?.menu?.userProfile ?? {},
  }
};

const chargingLimitConfig = (props) => {
  const { dispatch, dicData, listData, loading, userProfile, location: { pathname = '/' }, } = props;
  const searchRef = useRef(null)
  const [defaultBrand, setDefaultBrand ] = useState('')
  const [selectBrand, setSelectBrand ] = useState('')
  const [query, setQuery] = useState(DEFAULT_QUERY())
  const [brandOptions, setBrandOptions] = useState([])
  const [seriesOptions, setSeriesOptions] = useState([])
  const [groupOptions, setGroupOptions] = useState([])
  const { info, confirm } = Modal;
  const pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
    ...listData?.pagination ?? {},
  }

  const fetchParams = { type: 'chargingLimitConfig/getFetchPage', url: '/msrcs/chargingLimitConfig/list' }
  const refreshList = (brandCode: string) => {
    dispatch({
      type: fetchParams.type,
      payload: {
        url: fetchParams.url,
        ...query,
        brandCode,
        ...pagination
      }
    })  
  }

  useEffect(() => {
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res) => {
        setBrandOptions(res?.data || [])
        const brandCode = sessionStorage.getItem('chargingLimitConfigBrand') ?? res?.data[0].brandCode;
        setDefaultBrand(brandCode)
        setSelectBrand(brandCode)
        // searchRef?.current.setFieldsValue({brandCode: res?.data[0].brandCode})
        // searchRef?.current.submit()
        getSeriesOptions(brandCode)
        refreshList(brandCode)
        sessionStorage.removeItem('chargingLimitConfigBrand')
      },
    });
  }, [])

  const getSeriesOptions = (brandId: string) => {
    dispatch({
      type: 'http/getFetchPage',
      payload: {
        url: '/msdevice/base/vehicle/series/bybrand/list',
        brandId 
      },
      callback: (res: any) => {
        const data = res.data;
        setSeriesOptions(data.map((item: { seriesCode: any; seriesName: any }) => {
          return {
            value: item.seriesCode,
            label: item.seriesName,
          };
        }))
      }
    })
  }

  const getGroupOptions = (seriesCode: string) => {
    dispatch({
      type: 'http/postData',
      payload: {
        url: '/vehicle/group/findBySeriesCode',
        seriesCode,
      },
      callback: (res: any) => {
        const data = res.data;
        setGroupOptions(data.map((item: any) => {
          return {
            value: item.code,
            label: item.name,
          };
        }))
      }
    })
  }

  const handleBrandSelect = (brandId: string) => {
    setSeriesOptions([])
    setGroupOptions([])
    searchRef?.current.resetFields()
    if (!brandId) {
      return;
    }
    setSelectBrand(brandId)
    refreshList(brandId)
    //  获取车系数据
    getSeriesOptions(brandId)
  }

  const handleSeriesSelect = (seriesCode: string) => {
    setGroupOptions([])
    if (!seriesCode) {
      return;
    }
    //  获取车型组
    getGroupOptions(seriesCode)
  }

  const searchItems = [
    {
      title: '车系',
      type: 'select',
      key: 'seriesCode',
      selectOptions: seriesOptions,
      onChange: (e) => {
        handleSeriesSelect(e);
        searchRef?.current.setFieldsValue({groupCode: ''})
      },
    },
    {
      title: '车型组',
      type: 'select',
      selectOptions: groupOptions,
      key: 'groupCode',
    },
  ]

  const columns = [
    /* {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      render: (text: any, record: any, index: any) => {
        return index + 1 + (pagination.current - 1) * pagination.pageSize;
      },
    }, */
    {
      title: '车系',
      dataIndex: 'seriesName',
      ellipsis: {
        showTitle: false,
      },
      render: (text: any) => {
        return (
          <Tooltip placement="topLeft" title={text}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '车型组',
      dataIndex: 'groupName',
      ellipsis: {
        showTitle: false,
      },
      render: (text: any) => {
        return (
          <Tooltip placement="topLeft" title={text}>
            {text}
          </Tooltip>
        );
      },
    },
    {
      title: '慢充电流限制',
      dataIndex: 'currentLimit',
      render: (text: any) => {
        return (
          text ? text.split(',').map((item: string) => item + 'A').join(',') : '-'
        );
      },
    },
    {
      title: '充电soc下限',
      dataIndex: 'socLowerLimit',
      render: (text: any) => {
        return (
          text ? text*100 + '%' : '-'
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text: any) => {
        const res = text && text.trim() ? text.trim() : '-'
        return (
          <Tooltip placement="topLeft" title={res}>
            {res}
          </Tooltip>
        );
      },
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      render: (text: any) => {
        return (
          <Ellipsis length={20} tooltip>
            {text}
          </Ellipsis>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 150,
    },
    {
      title: '操作',
      width: 150,
      fixed: 'right',
      render: (text: any, record: any) => {
        const btns = [
          {
            title: '编辑',
            key: 'chargingLimitConfigEdit',
            auth: 'chargingLimitConfig_doEdit',
            onConfirm: () => {
              handleUpdateConfig(record)
            },
          },
          {
            title: '删除',
            key: 'chargingLimitConfigDel',
            type: 'danger',
            auth: 'chargingLimitConfig_delete',
            onConfirm: () => {
              confirm({
                title: '',
                icon: false,
                content: '确认删除当前充电限值配置？',
                // okText: '删除',
                onOk() {
                  dispatch({
                    type: 'chargingLimitConfig/getDataWithRes',
                    payload: {
                      url: '/msrcs/chargingLimitConfig/delete',
                      sid: record.sid
                    },
                    callback: () => {
                      message.success('删除成功')
                      refreshList(selectBrand)
                    }
                  })
                }
              })
            }
          }
        ]
        return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
      }
    }
  ]

  const tableProps = {
    columns: columns, //列表标题信息
    dataSource: listData.rows, //要渲染的数据信息
    loading: loading,
    rowKey: (record) => record.id, //接收每一行信息参数,设置每一行的key
    pagination: {
      ...pagination,
      showSizeChanger: true, //每页显示多少条
      showQuickJumper: true, //输数字快捷跳转
      showTotal: () => {
        return <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>;
      }, //展示页码信息栏
    },
    // scroll: { x: 'max-content' },
  };

  const handleUpdateConfig = (formData?: any) => {
    if (formData) {
      //  编辑
      dispatch({
        type: 'http/getDataWithRes',
        payload: { url: '/msrcs/chargingLimitConfig/detail', groupCode: formData?.groupCode },
        callback: res => {
          const data = res.data
          dispatch(
            routerRedux.push({
              pathname: '/remoteConfiguration/chargingLimitConfig/chargingLimitDetail',
              state: { isEdit: !!formData, formData: data },
            })
          );
        }
      })
    } else {
      //  新增
      const data = {
        brandCode: selectBrand,
        seriesCode: '',
        groupCode: '',
        socLowerLimit: '',
        currentLimit: [],
        remark: '',
      }
      dispatch(
        routerRedux.push({
          pathname: '/remoteConfiguration/chargingLimitConfig/chargingLimitDetail',
          state: { isEdit: !!formData, formData: data },
        })
      );
    }
  }

  return (
    <div>
      <div style={{margin: '0px 10px 10px 10px'}}>
        <div style={{display:'inline-block'}}>
          <span>品牌：</span>
        </div>
        <div style={{display:'inline-block'}}>
          <Select
            allowClear={false}
            placeholder="请选择品牌"
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
            onChange={handleBrandSelect}
            style={{width: '250px'}}
            key={defaultBrand}
            defaultValue={defaultBrand}
            fieldNames={{
              label: 'brandName',
              value: 'brandCode',
            }}
            options={brandOptions}
          >
          </Select>
        </div>
      </div>
      <Card className={styles.standardTable}>
        <PateoSearchForm
          searchItems={searchItems}
          fetchParams={fetchParams}
          saveFormValues={(val: any) => setQuery(val)}
          handleFormReset={() => setQuery(DEFAULT_QUERY())}
          extraArgs={{
            brandCode: selectBrand,
            current: 1,
            pageSize: 10,
          }}
          onRef={e => {
            searchRef.current = e.current;
          }}
        />
      </Card>
      <Card className={styles.standardTable}>
        <Button
          key="chargingLimitConfigAdd"
          icon={<PlusOutlined />}
          size="small"
          type="primary"
          style={{ marginBottom: '12px' }}
          onClick={() => handleUpdateConfig()}
        >新增</Button>
        <PateoTable
          extraHandle={true}
          tableProps={tableProps}
          fetchParams={fetchParams}
          formValues={query}
        />
      </Card>
    </div>
  )
}
export default connect(mapStateToProps)(chargingLimitConfig);
